package team.yidong.fenda.wx.Service.Impl;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import team.yidong.fenda.entity.Master;
import team.yidong.fenda.entity.User;
import team.yidong.fenda.repository.UserRepository;
import team.yidong.fenda.wx.Service.WxUserService;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by xuanlong on 2017/10/20.
 */
@Service
public class WxUserServiceImpl implements WxUserService {
    @Autowired
    UserRepository userRepository;

    @Override
    public User findByid(Integer UserId) {
        return userRepository.findOne(UserId);
    }

    @Override
    public JSONArray findByHospitalId(Integer hospitalId) {
        List<User> userList = userRepository.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();

                Predicate predicate = criteriaBuilder.equal(root.get("hospital").get("hospitalImgSet").get("id"), hospitalId);
                predicateList.add(predicate);
                criteriaQuery.where(predicateList.toArray(new Predicate[predicateList.size()]));
                return null;
            }
        });
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setExcludes(new String[]{"hospitalImgSet ", "hospitalPermissionSet", "hospitalFieldList", "userSet", "masterList", "wxOrder", "orderMoneyToList"});
        JSONArray jsonArray = JSONArray.fromObject(userList, jsonConfig);
        return jsonArray;
    }

    @Override
    public User findByOpenId(String openId) {
        return userRepository.findByUserOpenId(openId);
    }

    @Transactional
    @Override
    public void addUser(User user) {
        userRepository.save(user);
    }

    @Override
    public String checkUserIsBlack(String openId) {
        User user = userRepository.findByUserOpenId(openId);
        if ("是".equals(user.getIsBlack())){
            return "是";
        }else {
            return "否";
        }

    }
}
